﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity.Package;
using System.Configuration;
using Tools;

namespace BLL.CSocket
{
    public class PackageHandle
    {
        /// <summary>
        /// 解析数据包
        /// </summary>
        /// <param name="buffer">待解析的字节流</param>
        public static bool UnfoldingPackage(byte[] buffer,ClientThread curClient)
        {    
            try
            {
                if (buffer.Length > 0)  //够包头长度，则处理，否则返回继续接收
                {
                    PackHead packHead = PackageHandle.GetPackageHeader(buffer); //取包头

                    int bodyLength = int.Parse(packHead.PackLength.Trim()); //包长度

                    //接收的字节流超过包体长度，则取包体，否则返回继续接收
                    if ((buffer.Length - 39) >= bodyLength)
                    {
                        byte[] byteBody = PackageHandle.GetPackageBody(bodyLength, buffer);
                        
                        //分发包体业务
                        Business.ProcessBuiness.DistributeBusiness(byteBody, packHead, curClient);

                    }
                    else
                    {
                        LogHelper.WriteInfoLog("接收字节数少于包体长度，buffer.Length=" + buffer.Length + "bodyLength=" + bodyLength);
                        return false;
                    }

                }
                else
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("UnfoldingPackage方法-解析数据包发生异常。异常信息：" + ex.Message,ex);
                PackFailReturn pkFailReturn = new PackFailReturn();
                pkFailReturn.TradeCode = ((int) BLL.Business.TradeCode.网络错误).ToString();
                pkFailReturn.ResponseCode = ((int)BLL.Business.ResponseCode.其他错误).ToString().PadLeft(3,'0');
                pkFailReturn.PackHead = new PackHead("00","00000000000000", (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                SendFailurPackage(pkFailReturn,curClient);
            }
            return false;
        }     

        /// <summary>
        /// 组包操作
        /// </summary>
        /// <param name="obj">要组包的包体对象</param>
        /// <returns>组好的字节数组</returns>
        public static byte[] CombinationPackage(object obj)
        {
            byte[] package = null;
            
            try
            {
                package = Encoding.Default.GetBytes(obj.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("CombinationPackage方法-组包发生异常，异常信息：" + ex.Message, ex);
            }
            
            return package;
        }

        public static void SendFailurPackage(object obj, ClientThread client)
        {
            try
            {
                byte[] sendPackage = CSocket.PackageHandle.CombinationPackage(obj);
                if (client.Send(sendPackage))  //发送返回包
                    client.CloseSocket(); //断开链接
            }
            catch(Exception ex)
            {
                client.CloseSocket();
                LogHelper.WriteErrorLog("SendFailurPackage方法-发送失败包异常：" + ex.Message, ex);
            }
            
        }

        /// <summary>
        /// 获取包头
        /// </summary>
        /// <param name="buffer">接收的字节流</param>
        /// <returns></returns>
        public static PackHead GetPackageHeader(byte[] buffer)
        {
            PackHead pHead = new PackHead();
            try
            {
                byte[] packHead = new byte[33];
                Array.Copy(buffer, 0, packHead, 0, 33);
                string strHeader = System.Text.Encoding.Default.GetString(packHead);
               // string[] headerItem = strHeader.Split(new string[] { "|" },StringSplitOptions.None);
                pHead.PackCode = strHeader.Substring(0, 2);
                pHead.PointCode = strHeader.Substring(2, 4);
                pHead.PointPwd = strHeader.Substring(6, 5);
                pHead.ReservedField = strHeader.Substring(11, 1);
                pHead.PayWay = strHeader.Substring(12, 2);
                pHead.BankWaterNumber = strHeader.Substring(14, 14);
                pHead.PackLength = strHeader.Substring(28, 4);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("GetPackageHeader方法-获取包头异常：" + ex.Message, ex);
            }
            return pHead;
        }

        public static byte[] GetPackageBody(int bodyLength, byte[] buffer)
        {
            byte[] temp = new byte[bodyLength];
            Array.Copy(buffer, 33, temp, 0, bodyLength);
            return temp;
        }
        
        public static string GetTradeCode(byte[] body)
        {
            byte[] temp = new byte[3];
            Array.Copy(body, 0, temp, 0, 3);
            string tradeCode = System.Text.Encoding.Default.GetString(temp);
            return tradeCode;
        }

        public static object GetRequestBody(byte[] body)
        {
            object obj = null;
            string strBody = System.Text.Encoding.Default.GetString(body);
            string[] bodyItems=strBody.Split(new string[]{"|"},StringSplitOptions.None);
            switch((BLL.Business.TradeCode)int.Parse(bodyItems[0].Trim()))
            {
                case BLL.Business.TradeCode.对明细帐:
                    PackRequestDetailAccount pkDuiZhang = new PackRequestDetailAccount();
                    pkDuiZhang.TradeCode = bodyItems[0].Trim();
                    pkDuiZhang.DzDate = bodyItems[1].Trim();
                    pkDuiZhang.StrokeCount = bodyItems[2].Trim();
                    pkDuiZhang.PayMoneyHJ = bodyItems[3].Trim();
                    obj = pkDuiZhang;
                    break;
                case BLL.Business.TradeCode.缴费查询:
                    PackRequestSearch pkSearch = new PackRequestSearch();
                    pkSearch.TradeCode = bodyItems[0].Trim();
                    pkSearch.GasUserID = bodyItems[1].Trim();
                    pkSearch.Month = bodyItems[2].Trim();
                    pkSearch.Flag = bodyItems[3].Trim();
                    obj = pkSearch;
                    break;
                case BLL.Business.TradeCode.缴费冲帐:
                    PackRequestStrikeBalance pkStrike = new PackRequestStrikeBalance();
                    pkStrike.TradeCode = bodyItems[0].Trim();
                    pkStrike.GasUserID = bodyItems[1].Trim();
                    pkStrike.BankWaterNumber = bodyItems[2].Trim();
                    obj = pkStrike;
                    break;
                case BLL.Business.TradeCode.缴费业务:
                    PackRequestPayment pkPayment = new PackRequestPayment();
                    pkPayment.TradeCode = bodyItems[0].Trim();
                    pkPayment.GasUserID = bodyItems[1].Trim();
                    pkPayment.PayMoney = bodyItems[2].Trim();
                    pkPayment.Yjhj = bodyItems[3].Trim();
                    pkPayment.PayDate = bodyItems[4].Trim();
                    pkPayment.OperatorNumber = bodyItems[5].Trim();
                    pkPayment.PayMonth = bodyItems[6].Trim();
                    pkPayment.IsPrintFP = bodyItems[7].Trim();
                    obj = pkPayment;
                    break;
            }
            
            return obj;
        }
    }
}
